/**
* Copyright (c) 2016-2100 yunclouds
*/
package com.yunqian.redot.service;

import com.yunqian.exception.ServiceException;
import com.yunqian.redot.domain.Customers;
import com.yunqian.redot.repository.CustomersRepository;
import com.yunqian.service.BaseService;
import com.yunqian.util.bean.BeanUtil;
import com.yunqian.util.validate.Validator;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 客户信息表
 *
 * @author zsy
 * 2018-09-29 15:54:28
 */
@Service
@Log4j2
public class CustomersService extends BaseService<Customers, Long> {

    @Autowired
    private CustomersRepository customersRepository;

    public Customers findByName(String name){
        return customersRepository.findByName(name);
    }

    public Customers findByPhone(String phone){
        return customersRepository.findByPhone(phone);
    }

    public Customers findByOpenId(String openId){
        return customersRepository.findByOpenId(openId);
    }

    @Override
    public Customers save(Customers customers) {
        Customers cus  =customersRepository.findByOpenId(customers.getOpenId());
        if(Validator.isNotNull(cus)){
            BeanUtil.copyNotNullProperties(cus, customers);
            return super.update(cus);
        }
        return super.save(customers);
    }

    public void modifyPhone(String phone, String openId){
        checkPhone(phone, openId);
        Customers customers = Optional.ofNullable(customersRepository.findByOpenId(openId)).orElseThrow(() -> new ServiceException("用户不存在"));
        if(Validator.isNull(customers.getPhone())){
            customers.setPhone(phone);
            this.update(customers);
        }else if (Validator.equals(customers.getPhone(), phone)){
            return;
        }else {
            throw new ServiceException("已有绑定手机号，请用该手机号登录");
        }
    }

    public Customers getByPhoneAndOpenId(String phone, String openId){
        return customersRepository.findByPhoneAndOpenId(phone, openId);
    }

    public void checkPhone(String phone, String openId) {
        Customers customers = findByPhone(phone);
        if (Validator.isNotNull(customers) && !Validator.equals(customers.getOpenId(), openId)) {
            throw new ServiceException("该手机号已绑定其他账号");
        }
    }
}
